import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, Select } from 'antd';
import { queryShipper } from '../service';

const { Option } = Select;

interface CreateFormProps {
  onCancel: () => void;
  onOk: (data: any) => void;
}

interface stateData {
  list: any[];
}

const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 12 },
};

const CreateForm: React.FC<CreateFormProps> = (props) => {
  const { onCancel, onOk } = props;
  const [form] = Form.useForm();

  const [state, setState] = useState<stateData>({
    list: [],
  });
  const { list } = state;

  // 请求所有快递公司
  useEffect(() => {
    queryShipper().then(({ code, data }) => {
      if (code === 0) {
        setState({ list: data.list });
      }
    });
  }, []);

  const onFinish = async () => {
    const values = await form.validateFields();
    const { shipper_code } = values;
    const shipper = list.find((it) => it.code === shipper_code);
    Object.assign(values, { shipper_name: shipper.name });
    onOk(values);
  };

  return (
    <Modal
      destroyOnClose
      title="录入物流订单号"
      visible
      onOk={onFinish}
      onCancel={() => onCancel()}
    >
      <Form {...layout} form={form} name="basic" initialValues={{ remember: true }}>
        <Form.Item
          label="快递公司"
          name="shipper_code"
          rules={[{ required: true, message: '快递公司不能为空' }]}
        >
          <Select placeholder="请选择快递公司">
            {list.map((it) => (
              <Option value={it.code}>{it.name}</Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item
          label="物流订单号"
          name="shipper_id"
          rules={[{ required: true, message: '请输入物流订单号' }]}
        >
          <Input />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default CreateForm;
